package com.webframe.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.mlw.vlh.ValueList;
import net.mlw.vlh.ValueListInfo;
import net.mlw.vlh.web.mvc.ValueListHandlerHelper;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BasicDynaBean;
import org.apache.commons.beanutils.DynaProperty;

import com.webframe.util.StringUtil;

public class ValueListController extends BaseController
{

	ValueListHandlerHelper	valueListHandlerHelper;

	public ValueListHandlerHelper getValueListHandlerHelper()
	{
		return valueListHandlerHelper;
	}
	
	public void setValueListHandlerHelper(ValueListHandlerHelper valueListHandlerHelper)
	{
		this.valueListHandlerHelper = valueListHandlerHelper;
	}

	public ValueList getValueList(String adapter,HttpServletRequest request)
	{
		return getValueList(adapter, request,"");
	}

	/**
	 * @function:
	 * @param list
	 * @param sb
	 * @author lenovo 
	 */
	@SuppressWarnings("rawtypes")
	protected String wrapJson(ValueList list)
	{
		HashMap<String, Object> jsonmap = new HashMap<String, Object>();
		List<Map> data = new ArrayList<Map>();
		List list_ = list.getList();
		jsonmap.put("totalCount", list.getValueListInfo().getTotalNumberOfEntries());
		jsonmap.put("data", data);
		if(list_!=null && list_.size()>0){
			//有数据
			BasicDynaBean dynaBean = null;
			DynaProperty [] dynaProperties = null;
			for (Iterator iterator = list_.iterator(); iterator.hasNext();) {
				HashMap<String, Object> record = new LinkedHashMap<String, Object>();
				dynaBean = (BasicDynaBean) iterator.next();
				dynaProperties = dynaBean.getDynaClass().getDynaProperties();
				for(int i=0;i<dynaProperties.length;i++)
				{
					Object o = dynaBean.get(dynaProperties[i].getName());
					
					String value = (o == null)?"":o.toString();
					value=value.replaceAll("\r\n","");
				   record.put(dynaProperties[i].getName(), StringUtil.replaceSpecilCharForJson(value));
				}
				data.add(record);
			}
		}else{
			//无数据
			HashMap<String, Object> noRecord = new HashMap<String, Object>();
			noRecord.put("信息", "无数据");
			data.add(noRecord);
			jsonmap.put("norecord", true);
		}
		return JSONObject.fromObject(jsonmap).toString();
	}
	
	/**
	 * 输出结果
	 * 
	 * @param res
	 * @param sb
	 * @throws IOException
	 */
	protected void output(HttpServletResponse res, StringBuffer sb)
			throws IOException {
		res.setCharacterEncoding("UTF-8");
		res.setContentType("text/xml");
		PrintWriter out = res.getWriter();
		out.print(sb.toString());
		out.flush();
	}
	
	/**
	 * 下拉列表的情况
	 * @param sql 数据源
	 * @return json
	 */
	@SuppressWarnings("rawtypes")
	public StringBuffer dropdownlist(ValueList valueList) {
		List list =valueList.getList();
		BasicDynaBean dynaBean = null;
		StringBuffer sb = new StringBuffer();
		String name = "";
		String value = "";
		sb.append("[");
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			dynaBean = (BasicDynaBean) iterator.next();
			name = dynaBean.get("name") == null?"":dynaBean.get("name").toString();
			value = dynaBean.get("valtext") == null?"":dynaBean.get("valtext").toString();
			sb.append("{name:\""+name.trim()+"\",valtext:\""+StringUtil.replaceSpecilCharForJson(value.trim())+"\"}");
			if(iterator.hasNext()){
				sb.append(",");
			}
		}
		sb.append("]");
		return sb;
	}
	
	@SuppressWarnings({
				"rawtypes", "unchecked"})
	public ValueList getValueList(String adapter,HttpServletRequest request,String sql)
	{
		// get table info
		Map queries = new HashMap();
		ValueListInfo info = null;
		if (request != null) {
			Iterator it = request.getParameterMap().keySet().iterator();
			Object tmp;
			while (it.hasNext()) {
				tmp = it.next();
				if (!request.getParameter(tmp.toString()).equals("null"))
					queries.put(tmp, request.getParameter(tmp.toString()));
			}
			info = new ValueListInfo(queries);
			if(request.getParameter("limit")!=null)
			{
				info.setPagingNumberPer(Integer.parseInt(request.getParameter("limit")));
			}else{
				info.setPagingNumberPer(Integer.MAX_VALUE-1); //不分页时取integer最大值(原来是默认80会有数据不全问题)
			}
			if(request.getParameter("start")!=null)
			{
				info.setPagingPage(Integer.parseInt(request.getParameter("start"))/info.getPagingNumberPer()+1);
			}else{
				info.setPagingPage(0/info.getPagingNumberPer()+1); //不分页时默认按照从第1页开始
			}
		}else{
			info = new ValueListInfo(queries);
		}
		ValueList valueList = valueListHandlerHelper.getValueList(adapter, info,sql);
		if (valueList == null)
		{
			info.setPagingPage(info.getPagingPage() - 1);
			valueList = valueListHandlerHelper.getValueList(adapter, info,sql);
		}
		return valueList;
	}

	@SuppressWarnings({"rawtypes", "unchecked"})
	public ValueList getValueList(String adapter,HttpServletRequest request,Map map)
	{
		// get table info
		Map queries = new HashMap();
		Iterator it = request.getParameterMap().keySet().iterator();
		Object tmp;
		while(it.hasNext())
		{
			tmp=it.next();
			if(!request.getParameter(tmp.toString()).equals("null"))
				queries.put(tmp, request.getParameter(tmp.toString()));
		}
		if(map != null)
		{	
			queries.putAll(map);
		}
		ValueListInfo info = new ValueListInfo(queries);
		if(request.getParameter("limit")!=null)
		{
			info.setPagingNumberPer(Integer.parseInt(request.getParameter("limit")));
		}
		if(request.getParameter("start")!=null)
		{
			info.setPagingPage(Integer.parseInt(request.getParameter("start"))/info.getPagingNumberPer()+1);
		}
		ValueList valueList = valueListHandlerHelper.getValueList(adapter, info);
		if (valueList == null)
		{
			info.setPagingPage(info.getPagingPage() - 1);
			valueList = valueListHandlerHelper.getValueList(adapter, info);
		}
		return valueList;
	}
	
	@SuppressWarnings({
				"rawtypes", "unchecked"})
	public ValueList getAllValueList(String adapter, HttpServletRequest request)
	{
	   Map queries = new HashMap();
		Iterator it = request.getParameterMap().keySet().iterator();
		Object tmp;
		while(it.hasNext())
		{
			tmp=it.next();
			if(!request.getParameter(tmp.toString()).equals("null"))
			queries.put(tmp, request.getParameter(tmp.toString()));
		}
		ValueListInfo info = new ValueListInfo(queries);
		info.setPagingNumberPer(Integer.MAX_VALUE-1);
		ValueList valueList = valueListHandlerHelper.getValueList(adapter, info);
		if (valueList == null)
		{
			info.setPagingPage(info.getPagingPage() - 1);
			valueList = valueListHandlerHelper.getValueList(adapter, info);
		}
		return valueList;
	}
}
